<template>
  <div class="complaint__opeartion">
    <page-loading v-model="loadingStatus"></page-loading>
    <u-nav-bar :title="'投诉'" />
    <div class="complaint__opeartion__ct">
      <van-form @submit="onCommit">
        <div class="ct">
          <div class="type__area">
            <div class="title">单号类型</div>
            <div class="box">
              <div
                class="item"
                :class="orderType === item.value ? 'active' : ''"
                v-for="(item, index) in SearchBillTypeEm"
                :key="index"
                @click="onTabClick(item)"
              >
                {{ item.description }}
              </div>
            </div>
          </div>
          <div class="list">
            <van-field
              v-model="updateModal.billNo"
              input-align="right"
              :rules="updateModalRules.billNo"
              placeholder="请输入单号"
              @blur="onbillBlur"
            >
              <template #label>
                <div class="title">
                  <span style="color: #ff6459">*</span>
                  单号
                </div>
              </template>
            </van-field>
            <van-field
              v-model="updateModal.name"
              input-align="right"
              :rules="updateModalRules.name"
              placeholder="请选择"
              right-icon="arrow"
              :class="nameSelectedClass"
              disabled
              @click="onClickSelected('name')"
            >
              <template #label>
                <div class="title">
                  <span style="color: #ff6459">*</span>
                  投诉对象
                </div>
              </template>
            </van-field>
            <van-field
              v-model="updateModal.complaintType"
              input-align="right"
              right-icon="arrow"
              :rules="updateModalRules.complaintType"
              :class="updateModal.complaintType ? 'active' : ''"
              placeholder="请选择"
              @click="onClickSelected('complaintType')"
              disabled
            >
              <template #label>
                <div class="title" style="width: 100%">
                  <span style="color: #ff6459">*</span>
                  投诉类型
                </div>
              </template>
            </van-field>
            <div class="remark">
              <van-field
                v-model="updateModal.remark"
                maxlength="200"
                :rules="updateModalRules.remark"
                type="textarea"
                placeholder="请描述具体情况，有助于投诉快速处理"
              >
                <template #label>
                  <div class="title">
                    <span style="color: #ff6459">*</span>
                    投诉描述
                  </div>
                </template>
              </van-field>
              <div class="text__num">
                <span>{{ updateModal.remark.length }}</span>
                <span class="line">/</span>
                <span>200</span>
              </div>
            </div>
          </div>
        </div>
        <van-button class="btn" :class="canCommit ? 'btn__active' : ''" native-type="submit">提交</van-button>
      </van-form>
    </div>
    <van-popup v-model:show="popupObj.show" position="bottom">
      <div class="fuzzySearch">
        <div class="fuzzySearch__ct">
          <van-radio-group v-model="popupObj.currentValue">
            <van-cell-group class="bankList">
              <van-cell :title="item.description" clickable v-for="item in popupObj.list" :key="item.value">
                <template #right-icon>
                  <van-radio :name="item.value" @click="onSelected(item)" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, watchEffect, ref } from 'vue'
import { Popup, Radio, RadioGroup } from 'vant'
import store from '@/store/index'
import NavBar from '@/components/NavBar.vue'
import { UpdateComplaintType, SearchBillType, SelectedListType } from './utils/types'
import { SearchBillTypeEm, LabelTypesEm } from './utils/enums'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import PageLoding from '@/components/PageLoading.vue'

export default defineComponent({
  name: 'ComplaintUpdate',
  components: {
    'u-nav-bar': NavBar,
    'van-popup': Popup,
    'van-radio': Radio,
    'van-radio-group': RadioGroup,
    'page-loading': PageLoding
  },
  setup() {
    const router = useRouter()

    // 订单类型
    const orderType = ref<number>(SearchBillTypeEm.ORDER.value)

    const loadingStatus = ref(false)

    const updateModal = reactive<UpdateComplaintType>({
      billId: '',
      billNo: '',
      complaintType: '',
      mobile: '',
      name: '',
      remark: ''
    })

    const updateModalRules = {
      billNo: [
        {
          required: true,
          message: '请填写单号'
        }
      ],
      name: [
        {
          required: true,
          message: '请选择投诉对象'
        }
      ],
      complaintType: [
        {
          required: true,
          message: '请选择投诉类型'
        }
      ],
      remark: [
        {
          required: true,
          message: '投诉描述不能为空'
        },
        {
          message: '投诉描述不能少于15字',
          validator: (val: string) => {
            if (val.length < 15) {
              return false
            }
            return true
          }
        }
      ]
    }

    const popupObj = reactive<{
      show: boolean
      currentValue: string | number
      list: SelectedListType[]
      currentField: 'name' | 'complaintType'
    }>({
      show: false, // 是否显示单选弹窗
      currentValue: '', // 当前单选弹窗选中项
      currentField: 'name', // 当前字段
      list: [] // 当前列表
    })

    // 选择列表
    const selectedCollected = reactive<{ complaintType: SelectedListType[]; name: SelectedListType[] }>({
      complaintType: [], // 投诉类型
      name: [] // 投诉对象
    })

    // 投诉对象class
    const nameSelectedClass = ref('')

    // 是否能提交
    const canCommit = ref<boolean>(false)

    // 点击选择列表
    const onClickSelected = (type: 'name' | 'complaintType'): void => {
      if (type === 'name' && !updateModal.billNo) {
        Toast.fail('请先输入单号')
        return
      }
      popupObj.list = selectedCollected[type] || []
      popupObj.currentValue = updateModal[type] || ''
      popupObj.currentField = type
      if (popupObj.list.length < 1) {
        return
      }
      popupObj.show = true
    }

    // 选择单选框
    const onSelected = (item: SelectedListType): void => {
      popupObj.show = false
      popupObj.currentValue = item.value
      updateModal[popupObj.currentField] = item.value as string
      switch (popupObj.currentField) {
        case 'name': // 投诉对象
          updateModal.mobile = item.target?.mobile ?? ''
          break
        default:
      }
    }

    // 构建列表弹窗数据
    const buildSelectedData = (data: any[], valueField: string, descriptionField: string): SelectedListType[] => {
      const list: SelectedListType[] = []
      data.forEach(item => {
        list.push({
          value: item[valueField],
          description: item[descriptionField],
          target: item
        })
      })
      return list
    }

    // 单号失去焦点时触发
    const onbillBlur = async (): Promise<void> => {
      popupObj.currentValue = ''
      updateModal.name = ''
      updateModal.mobile = ''
      selectedCollected.name = []
      if (!updateModal.billNo) {
        return
      }
      loadingStatus.value = true
      const params: SearchBillType = {
        exact: 1,
        orderNo: updateModal.billNo,

        orderType: orderType.value
      }
      const result = await store.dispatch('complaint/handleTransportBillComplaintListBySearch', params)
      loadingStatus.value = false
      if (!result || result.length < 1) {
        // 判断投诉对象是否有返回 若无 则该订单不可投诉
        Toast.fail('该单不可投诉')
        return
      }
      const data = result.length > 0 ? result[0] : {}
      selectedCollected.name = buildSelectedData(data?.complainantParams ?? [], 'userName', 'userName')
      updateModal.billId = data?.id ?? ''
    }

    // 获取投诉类型列表 status 0 启用 1禁用 tagAscript 2货主
    const getComplaintTypes = async (): Promise<void> => {
      const params = {
        tagType: LabelTypesEm.COMPLAINT.value,
        status: 0,
        tagAscript: 2,
        pageNo: 1,
        PageSize: 100
      }
      const result = await store.dispatch('system/handleSysTagLibraryPage', params)
      const list = result?.rows ?? []
      selectedCollected.complaintType = buildSelectedData(list, 'tagName', 'tagName')
    }

    // 提交
    const onCommit = async (): Promise<void> => {
      const result = await store.dispatch('complaint/handleTransportBillComplaintAdd', updateModal)
      if (result) {
        Toast.success('提交成功')
        setTimeout(() => {
          router.go(-1)
        }, 2000)
      }
    }

    // 切换导航栏
    const onTabClick = (item: { value: number; description: string }): void => {
      orderType.value = item.value
      popupObj.currentValue = ''
      selectedCollected.name = []
      updateModal.name = ''
      updateModal.mobile = ''
      updateModal.complaintType = ''
      updateModal.billNo = ''
      updateModal.remark = ''
    }

    // 监听必填项目有没有填完
    watchEffect(() => {
      if (updateModal.billNo && updateModal.name && updateModal.remark && updateModal.complaintType) {
        canCommit.value = true
      } else {
        canCommit.value = false
      }
    })

    getComplaintTypes()

    watchEffect(() => {
      let _nameSelectedClass = ''
      if (updateModal.name) {
        _nameSelectedClass += 'active'
      }
      if (selectedCollected.name.length < 1) {
        _nameSelectedClass += 'cell__disabled'
      }
      nameSelectedClass.value = _nameSelectedClass
    })

    return {
      SearchBillTypeEm,
      updateModal,
      popupObj,
      canCommit,
      updateModalRules,
      onClickSelected,
      onCommit,
      onbillBlur,
      onSelected,
      onTabClick,
      orderType,
      loadingStatus,
      nameSelectedClass
    }
  }
})
</script>

<style lang="scss">
.complaint__opeartion {
  position: relative;
  .active {
    .van-field__body input,
    .van-field__control:disabled {
      color: #040405 !important;
      -webkit-text-fill-color: #040405 !important;
    }
  }
  .van-cell {
    padding: 13px 0;
    .van-field__error-message {
      text-align: right;
    }
  }
  .cell__disabled {
    .title,
    span,
    .van-icon {
      color: #c8c9cc !important;
    }
  }
  .remark {
    .van-cell__title {
      width: 100%;
    }
    .van-cell__value {
      width: 100%;
    }
    .van-cell {
      display: flex;
      flex-direction: column;
      .van-cell__value {
        margin-top: 15px;
      }
      textarea {
        min-height: 100px;
        height: 80px;
        box-sizing: border-box;
        padding: 10px;
        background: rgba(159, 162, 175, 0.08);
        border-radius: 10px;
        border: 1px solid rgba(159, 162, 175, 0.2);
      }
    }
  }
  .van-cell::after {
    right: 0 !important;
    left: 0 !important;
  }
  .van-popup {
    height: 80%;
  }
  .fuzzySearch {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 12px;
    display: flex;
    flex-direction: column;
    overflow-y: scroll;
    &__ct {
      width: 100%;
    }
  }
}
</style>

<style lang="scss" scoped>
@import '@/style/variables.scss';
@import '@/style/mixins.scss';
.complaint__opeartion {
  position: fixed;
  top: 0;
  bottom: 0;
  width: 100%;
  z-index: 100;
  @include flex-cloumn-width-height-100;
  background-color: $background-color-base;
  .van-popup {
    width: 100%;
    height: 80%;
  }

  &__ct {
    @include flex-scroll-content-pd(24px 12px 0 12px);
    .ct {
      width: 100%;
      background: #ffffff;
      box-shadow: 0px 2px 10px 0px rgba(93, 184, 255, 0.07);
      border-radius: 10px;
      box-sizing: border-box;
      padding: 15px 12px 0 12px;
    }
    background: #ffffff;
    .space__box {
      width: 100%;
      height: 10px;
    }
    .type__area {
      width: 100%;
      position: relative;
      padding-bottom: 15px;
      &::after {
        position: absolute;
        box-sizing: border-box;
        content: ' ';
        pointer-events: none;
        right: 0;
        bottom: 0;
        left: 0;
        border-bottom: 0.02667rem solid var(--van-cell-border-color);
        transform: scaleY(0.5);
      }
      .title {
        font-size: 14px;
        font-weight: 400;
        color: #575c72;
        line-height: 20px;
        margin-bottom: 10px;
      }
      .box {
        display: flex;
        align-items: center;

        .item {
          width: 76px;
          height: 30px;
          background: #f5f5f7;
          border-radius: 17px;
          font-size: 14px;
          font-weight: 400;
          color: #575c72;
          line-height: 30px;
          text-align: center;
          margin-right: 14px;
        }
        .active {
          background: linear-gradient(125deg, #74cdff 0%, #409eff 100%);
          color: white;
        }
      }
    }
    .list {
      .title {
        font-size: 14px;
        font-weight: 400;
        color: #575c72;
        line-height: 24px;
      }
      .remark {
        position: relative;
        .title {
          font-size: 14px;
          font-weight: 400;
          color: #101736;
        }
      }
      .text__num {
        display: flex;
        justify-content: flex-end;
        position: absolute;
        right: 10px;
        top: 126px;
        span {
          font-size: 14px;
          font-weight: 400;
          color: #575c72;
          line-height: 20px;
        }
        .line {
          padding: 0 2px;
        }
      }
    }
    .btn {
      width: 325px;
      margin: 50px auto 0 auto;
      height: 48px;
      background: linear-gradient(125deg, #74cdff 0%, #409eff 100%);
      border-radius: 6px;
      text-align: center;
      line-height: 48px;
      opacity: 0.5;
      font-size: 16px;
      font-weight: 500;
      color: #ffffff;
      display: block;
    }
    .btn__active {
      opacity: 1;
    }
  }
}
</style>
